/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.apache.plc4x.java.bacnetip.readwrite;

import static org.apache.plc4x.java.spi.codegen.fields.FieldReaderFactory.*;
import static org.apache.plc4x.java.spi.codegen.fields.FieldWriterFactory.*;
import static org.apache.plc4x.java.spi.codegen.io.DataReaderFactory.*;
import static org.apache.plc4x.java.spi.codegen.io.DataWriterFactory.*;
import static org.apache.plc4x.java.spi.generation.StaticHelper.*;

import java.time.*;
import java.util.*;
import org.apache.plc4x.java.api.exceptions.*;
import org.apache.plc4x.java.api.value.*;
import org.apache.plc4x.java.spi.codegen.*;
import org.apache.plc4x.java.spi.codegen.fields.*;
import org.apache.plc4x.java.spi.codegen.io.*;
import org.apache.plc4x.java.spi.generation.*;

// Code generated by code-generation. DO NOT EDIT.

public class APDUComplexAck extends APDU implements Message {

  // Accessors for discriminator values.
  public ApduType getApduType() {
    return ApduType.COMPLEX_ACK_PDU;
  }

  // Properties.
  protected final boolean segmentedMessage;
  protected final boolean moreFollows;
  protected final short originalInvokeId;
  protected final Short sequenceNumber;
  protected final Short proposedWindowSize;
  protected final BACnetServiceAck serviceAck;

  /**
   * When we read the first segment we want the service choice to be part of the bytes so we only
   * read it > 0
   */
  protected final BACnetConfirmedServiceChoice segmentServiceChoice;

  protected final byte[] segment;
  // Reserved Fields
  private Byte reservedField0;

  public APDUComplexAck(
      boolean segmentedMessage,
      boolean moreFollows,
      short originalInvokeId,
      Short sequenceNumber,
      Short proposedWindowSize,
      BACnetServiceAck serviceAck,
      BACnetConfirmedServiceChoice segmentServiceChoice,
      byte[] segment) {
    super();
    this.segmentedMessage = segmentedMessage;
    this.moreFollows = moreFollows;
    this.originalInvokeId = originalInvokeId;
    this.sequenceNumber = sequenceNumber;
    this.proposedWindowSize = proposedWindowSize;
    this.serviceAck = serviceAck;
    this.segmentServiceChoice = segmentServiceChoice;
    this.segment = segment;
  }

  public boolean getSegmentedMessage() {
    return segmentedMessage;
  }

  public boolean getMoreFollows() {
    return moreFollows;
  }

  public short getOriginalInvokeId() {
    return originalInvokeId;
  }

  public Short getSequenceNumber() {
    return sequenceNumber;
  }

  public Short getProposedWindowSize() {
    return proposedWindowSize;
  }

  public BACnetServiceAck getServiceAck() {
    return serviceAck;
  }

  /**
   * When we read the first segment we want the service choice to be part of the bytes so we only
   * read it > 0
   */
  public BACnetConfirmedServiceChoice getSegmentServiceChoice() {
    return segmentServiceChoice;
  }

  public byte[] getSegment() {
    return segment;
  }

  public int getApduHeaderReduction() {
    return (int) ((2) + ((((getSegmentedMessage()) ? 2 : 0))));
  }

  public int getSegmentReduction() {
    return (int)
        (((((getSegmentServiceChoice()) != (null)))
            ? ((getApduHeaderReduction()) + (1))
            : getApduHeaderReduction()));
  }

  @Override
  protected void serializeAPDUChild(WriteBuffer writeBuffer) throws SerializationException {
    PositionAware positionAware = writeBuffer;
    boolean _lastItem = ThreadLocalHelper.lastItemThreadLocal.get();
    writeBuffer.pushContext("APDUComplexAck");

    // Simple Field (segmentedMessage)
    writeSimpleField("segmentedMessage", segmentedMessage, writeBoolean(writeBuffer));

    // Simple Field (moreFollows)
    writeSimpleField("moreFollows", moreFollows, writeBoolean(writeBuffer));

    // Reserved Field (reserved)
    writeReservedField(
        "reserved",
        reservedField0 != null ? reservedField0 : (byte) 0,
        writeUnsignedByte(writeBuffer, 2));

    // Simple Field (originalInvokeId)
    writeSimpleField("originalInvokeId", originalInvokeId, writeUnsignedShort(writeBuffer, 8));

    // Optional Field (sequenceNumber) (Can be skipped, if the value is null)
    writeOptionalField("sequenceNumber", sequenceNumber, writeUnsignedShort(writeBuffer, 8));

    // Optional Field (proposedWindowSize) (Can be skipped, if the value is null)
    writeOptionalField(
        "proposedWindowSize", proposedWindowSize, writeUnsignedShort(writeBuffer, 8));

    // Virtual field (doesn't serialize anything, just makes the value available)
    int apduHeaderReduction = getApduHeaderReduction();
    writeBuffer.writeVirtual("apduHeaderReduction", apduHeaderReduction);

    // Optional Field (serviceAck) (Can be skipped, if the value is null)
    writeOptionalField("serviceAck", serviceAck, writeComplex(writeBuffer));

    // Optional Field (segmentServiceChoice) (Can be skipped, if the value is null)
    writeOptionalEnumField(
        "segmentServiceChoice",
        "BACnetConfirmedServiceChoice",
        segmentServiceChoice,
        writeEnum(
            BACnetConfirmedServiceChoice::getValue,
            BACnetConfirmedServiceChoice::name,
            writeUnsignedShort(writeBuffer, 8)),
        (getSegmentedMessage()) && ((getSequenceNumber()) != (0)));

    // Virtual field (doesn't serialize anything, just makes the value available)
    int segmentReduction = getSegmentReduction();
    writeBuffer.writeVirtual("segmentReduction", segmentReduction);

    // Array Field (segment)
    writeByteArrayField("segment", segment, writeByteArray(writeBuffer, 8));

    writeBuffer.popContext("APDUComplexAck");
  }

  @Override
  public int getLengthInBytes() {
    return (int) Math.ceil((float) getLengthInBits() / 8.0);
  }

  @Override
  public int getLengthInBits() {
    int lengthInBits = super.getLengthInBits();
    APDUComplexAck _value = this;
    boolean _lastItem = ThreadLocalHelper.lastItemThreadLocal.get();

    // Simple field (segmentedMessage)
    lengthInBits += 1;

    // Simple field (moreFollows)
    lengthInBits += 1;

    // Reserved Field (reserved)
    lengthInBits += 2;

    // Simple field (originalInvokeId)
    lengthInBits += 8;

    // Optional Field (sequenceNumber)
    if (sequenceNumber != null) {
      lengthInBits += 8;
    }

    // Optional Field (proposedWindowSize)
    if (proposedWindowSize != null) {
      lengthInBits += 8;
    }

    // A virtual field doesn't have any in- or output.

    // Optional Field (serviceAck)
    if (serviceAck != null) {
      lengthInBits += serviceAck.getLengthInBits();
    }

    // Optional Field (segmentServiceChoice)
    if (segmentServiceChoice != null) {
      lengthInBits += 8;
    }

    // A virtual field doesn't have any in- or output.

    // Array field
    if (segment != null) {
      lengthInBits += 8 * segment.length;
    }

    return lengthInBits;
  }

  public static APDUBuilder staticParseAPDUBuilder(ReadBuffer readBuffer, Integer apduLength)
      throws ParseException {
    readBuffer.pullContext("APDUComplexAck");
    PositionAware positionAware = readBuffer;
    boolean _lastItem = ThreadLocalHelper.lastItemThreadLocal.get();

    boolean segmentedMessage = readSimpleField("segmentedMessage", readBoolean(readBuffer));

    boolean moreFollows = readSimpleField("moreFollows", readBoolean(readBuffer));

    Byte reservedField0 = readReservedField("reserved", readUnsignedByte(readBuffer, 2), (byte) 0);

    short originalInvokeId = readSimpleField("originalInvokeId", readUnsignedShort(readBuffer, 8));

    Short sequenceNumber =
        readOptionalField("sequenceNumber", readUnsignedShort(readBuffer, 8), segmentedMessage);

    Short proposedWindowSize =
        readOptionalField("proposedWindowSize", readUnsignedShort(readBuffer, 8), segmentedMessage);
    int apduHeaderReduction =
        readVirtualField("apduHeaderReduction", int.class, (2) + ((((segmentedMessage) ? 2 : 0))));

    BACnetServiceAck serviceAck =
        readOptionalField(
            "serviceAck",
            readComplex(
                () ->
                    BACnetServiceAck.staticParse(
                        readBuffer, (long) ((apduLength) - (apduHeaderReduction))),
                readBuffer),
            !(segmentedMessage));
    // Validation
    if (!((((!(segmentedMessage)) && ((serviceAck) != (null)))) || (segmentedMessage))) {
      throw new ParseValidationException("service ack should be set");
    }

    BACnetConfirmedServiceChoice segmentServiceChoice =
        readOptionalField(
            "segmentServiceChoice",
            readEnum(BACnetConfirmedServiceChoice::enumForValue, readUnsignedShort(readBuffer, 8)),
            (segmentedMessage) && ((sequenceNumber) != (0)));
    int segmentReduction =
        readVirtualField(
            "segmentReduction",
            int.class,
            ((((segmentServiceChoice) != (null)))
                ? ((apduHeaderReduction) + (1))
                : apduHeaderReduction));

    byte[] segment =
        readBuffer.readByteArray(
            "segment",
            Math.toIntExact(
                ((segmentedMessage)
                    ? (((((apduLength) > (0))) ? ((apduLength) - (segmentReduction)) : 0))
                    : 0)));

    readBuffer.closeContext("APDUComplexAck");
    // Create the instance
    return new APDUComplexAckBuilderImpl(
        segmentedMessage,
        moreFollows,
        originalInvokeId,
        sequenceNumber,
        proposedWindowSize,
        serviceAck,
        segmentServiceChoice,
        segment,
        reservedField0);
  }

  public static class APDUComplexAckBuilderImpl implements APDU.APDUBuilder {
    private final boolean segmentedMessage;
    private final boolean moreFollows;
    private final short originalInvokeId;
    private final Short sequenceNumber;
    private final Short proposedWindowSize;
    private final BACnetServiceAck serviceAck;
    private final BACnetConfirmedServiceChoice segmentServiceChoice;
    private final byte[] segment;
    private final Byte reservedField0;

    public APDUComplexAckBuilderImpl(
        boolean segmentedMessage,
        boolean moreFollows,
        short originalInvokeId,
        Short sequenceNumber,
        Short proposedWindowSize,
        BACnetServiceAck serviceAck,
        BACnetConfirmedServiceChoice segmentServiceChoice,
        byte[] segment,
        Byte reservedField0) {
      this.segmentedMessage = segmentedMessage;
      this.moreFollows = moreFollows;
      this.originalInvokeId = originalInvokeId;
      this.sequenceNumber = sequenceNumber;
      this.proposedWindowSize = proposedWindowSize;
      this.serviceAck = serviceAck;
      this.segmentServiceChoice = segmentServiceChoice;
      this.segment = segment;
      this.reservedField0 = reservedField0;
    }

    public APDUComplexAck build() {
      APDUComplexAck aPDUComplexAck =
          new APDUComplexAck(
              segmentedMessage,
              moreFollows,
              originalInvokeId,
              sequenceNumber,
              proposedWindowSize,
              serviceAck,
              segmentServiceChoice,
              segment);
      aPDUComplexAck.reservedField0 = reservedField0;
      return aPDUComplexAck;
    }
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (!(o instanceof APDUComplexAck)) {
      return false;
    }
    APDUComplexAck that = (APDUComplexAck) o;
    return (getSegmentedMessage() == that.getSegmentedMessage())
        && (getMoreFollows() == that.getMoreFollows())
        && (getOriginalInvokeId() == that.getOriginalInvokeId())
        && (getSequenceNumber() == that.getSequenceNumber())
        && (getProposedWindowSize() == that.getProposedWindowSize())
        && (getServiceAck() == that.getServiceAck())
        && (getSegmentServiceChoice() == that.getSegmentServiceChoice())
        && (getSegment() == that.getSegment())
        && super.equals(that)
        && true;
  }

  @Override
  public int hashCode() {
    return Objects.hash(
        super.hashCode(),
        getSegmentedMessage(),
        getMoreFollows(),
        getOriginalInvokeId(),
        getSequenceNumber(),
        getProposedWindowSize(),
        getServiceAck(),
        getSegmentServiceChoice(),
        getSegment());
  }

  @Override
  public String toString() {
    WriteBufferBoxBased writeBufferBoxBased = new WriteBufferBoxBased(true, true);
    try {
      writeBufferBoxBased.writeSerializable(this);
    } catch (SerializationException e) {
      throw new RuntimeException(e);
    }
    return "\n" + writeBufferBoxBased.getBox().toString() + "\n";
  }
}
